using System.Linq;

namespace GameToolkit.BehaviourTree
{

    /// <summary>
    /// 行为树控制节点
    /// </summary>
    public abstract partial class ControllerNode : ExecutableEntry, IExecutableParent
    {
        bool mIsLoopController;
        ExecutableEntry[] mChildren;
        internal bool IsLoopController => mIsLoopController;
        public int ChildCount => mChildren == null ? 0 : mChildren.Length;
        public ExecutableEntry GetChild(int index) { return mChildren[index]; }
        internal override void InitializeSelf(CreateBehaviourTreeContext context)
        {
            base.InitializeSelf(context);
            mIsLoopController = this is ILoopController;
            mChildren = context.childrenBuffer.ToArray();
            //mIsEmptySuccess = context.composite is ControllerComposite cc && cc.IsSuccessForEmptyChild;
        }

        internal ExecutableEntry InvokeNextNode(BehaviourTreePlayer player)
        {
            ExecutableEntry node = null;
            NodeState stat;
            if (ChildCount > 0)
                stat = GetNextBehaviour(player, out node);
            else
                stat = NodeState.Failed;
            if (stat == NodeState.Running && (mIsLoopController || node != null))
            {
                return node;
            }
            else
            {
                State = stat == NodeState.Running || stat == NodeState.Success ? NodeState.Success : NodeState.Failed;
                return null;
            }
        }

    }

}
